
<template>
  <div class='app-container'>
    <el-row type="flex" :gutter="12">
      <el-col :span="4">
        <div class="left-tree">
          <el-tree :data="appinfos" highlight-current :props="defaultProps" @current-change="onTreeSelected" empty-text="无微信APP数据,请先添加微信APP相关信息" node-key="appid" default-expand-all>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="right-grid">
          <div class='button-container'>
            <el-button class='filter-item' type='primary' @click='openEditShopDialog(null,true)' :disabled="selectedApp==null" icon='edit'>新增</el-button>
          </div>
          <el-table ref="shopTable" @selection-change="onSelectionChanged" :data="GridPageList" v-loading.body="gridDataIsLoading" element-loading-text="数据加载中..." border fit highlight-current-row>
            <el-table-column align="center" label='序号' width="80">
              <template scope="scope">
                {{scope.$index + 1}}
              </template>
            </el-table-column>
            <el-table-column label="店铺名称" width="100">
              <template scope="scope">
                {{scope.row.name}}
              </template>
            </el-table-column>
            <el-table-column label="店铺公告" width="150">
              <template scope="scope">
                {{scope.row.bulletin}}
              </template>
            </el-table-column>
            <el-table-column label="店铺备注" width="180">
              <template scope="scope">
                {{scope.row.description}}
              </template>
            </el-table-column>
            <el-table-column label="最低起送金额" width="130">
              <template scope="scope">
                {{scope.row.minPrice}}
              </template>
            </el-table-column>
            <el-table-column label="配送费用" width="100">
              <template scope="scope">
                {{scope.row.deliveryPrice}}
              </template>
            </el-table-column>

            <el-table-column label="地址" width="200">
              <template scope="scope">
                {{scope.row.gpsaddress+scope.row.detailaddress}}
              </template>
            </el-table-column>
            <!-- <el-table-column label="优惠" width="250">
                                                                                                <template scope="scope">
                                                                                                  <template v-for="(support,index) in scope.row.supports">
                                                                                                    <el-tag type='primary' :key="index" close-transition>{{support.supportremark}}
                                                                                                    </el-tag>
                                                                                                  </template>
                                                                                                </template>
                                                                                              </el-table-column> -->
            <el-table-column align="center" label="操作">
              <template scope="scope">
                <el-button icon="edit" size="small" type="primary" @click=openEditShopDialog(scope.row,false)>编辑</el-button>
                <el-button icon="setting" size="small" @click=setShopGoods(scope.row)>货品</el-button>
                <el-button icon="delete" type="danger" size="small" @click="deleteShop(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-show="!gridDataIsLoading" class="pagination-container">
            <el-pagination @size-change="onPageSizeChanged" @current-change="onPageNoChanged" :current-page.sync="paginationConfig.currentQueryPage" :page-sizes="[10,20,30, 50]" :page-size="paginationConfig.selectedPageSize" layout="total, sizes, prev, pager, next, jumper" :total="dataCount">
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog title='编辑微商城店铺信息' :visible.sync='editShopDialogOpend' class="shop-dialog" @close='closeShopForm'>
      <el-form :model="editingShop" ref="shopForm" :rules="rules" :show-message="validateable">
        <el-form-item label='店铺名称' prop="name">
          <el-input v-model='editingShop.name' placeholder="请输入店铺名称"></el-input>
        </el-form-item>
        <span class="lable-span">店铺LOGO</span>
        <div class="shop_img">
          <el-upload :show-file-list="false" class="avatar-uploader" :action="uploadUrl" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="editingShop.avatar!=''" :src="editingShop.avatar" class="avatar"> </img>
            <div v-else class="deaultavatar"> </div>
          </el-upload>
        </div>
        <el-form-item label='店铺公告' prop="bulletin">
          <el-input v-model='editingShop.bulletin' placeholder="店铺公告"></el-input>
        </el-form-item>
        <el-form-item label='店铺备注' prop="description">
          <el-input v-model='editingShop.description' placeholder="店铺备注"></el-input>
        </el-form-item>
        <el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label='订单起送价格' prop="minPrice">
                <el-input-number v-model="editingShop.minPrice" :min="0" :controls="true" :step="5"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label='订单配送费' prop="deliveryPrice">
                <el-input-number v-model="editingShop.deliveryPrice" :min="0" :controls="true" :step="5"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label='店铺地址' prop="gpsaddress">
          <el-autocomplete placeholder="小区/写字楼/学校等" style="width:100%" v-model="editingShop.gpsaddress" :fetch-suggestions="querySearchAsync" :trigger-on-focus="false" @select="handleSelect"></el-autocomplete>
        </el-form-item>
        <el-input placeholder="详细地址（如门牌号等）" v-model="editingShop.detailaddress"></el-input>

        <el-form-item>
          <div class="lable-span">店铺优惠信息</div>
          <li v-for="(support,index) in editingShop.uisupports" :key="index">
            <el-row :gutter="5" style="margin-top:12px;margin-bottom:12px;">
              <el-col :span="4">
                <el-select v-model="support.supporttype" placeholder="请选择优惠方式">
                  <el-option label="立减" value="decrease"></el-option>
                  <el-option label="折扣" value="discount"></el-option>
                  <el-option label="特价" value="special"></el-option>
                </el-select>
              </el-col>
              <el-col :span="20">
                <el-input placeholder="请输入优惠描述文案" v-model="support.supportremark">
                  <el-button slot="append" icon="close" @click="removeSupport(index)"></el-button>
                </el-input>
              </el-col>
            </el-row>
          </li>
          <el-button type="primary" icon="plus" plain size="small" @click='addSupports'>添加</el-button>
        </el-form-item>
        <el-form-item>
          <div class="lable-span">店铺描述文案</div>
          <ul>
            <li v-for="(info,index) in editingShop.uiinfos" :key="index" style="margin-top:12px;margin-bottom:12px;">
              <el-input placeholder="请输入店铺描述文案" v-model="info.infotext">
                <el-button slot="append" icon="close" @click='removeInfo(index)'></el-button>
              </el-input>
            </li>
          </ul>
          <el-button type="primary" icon="plus" plain size="small" @click='addInfos'>添加</el-button>
        </el-form-item>
      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleEditAppSubmit'>确定</el-button>
        <el-button @click='editShopDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog>

    <!-- 指定商户默认货品 -->
    <el-dialog title='指定门店下属货品' :visible.sync='defaultGoodDialogOpend'>
      <div class="good-transfer">
        <el-transfer v-model="selecteGoods" :titles="['未选货品', '已选货品']" :props="{ key: 'gsid', label: 'gsname'}" :data="allGoods"></el-transfer>
      </div>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleSetGoodsubmit'>确定</el-button>
        <el-button @click='defaultGoodDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { Utils } from '@/utils/utils.js';
import NProgress from 'nprogress'; // Progress 进度条
export default {
  name: 'wechatmallshopset',
  data() {
    const validateaddressrequired = (rule, value, callback) => {
      if (this.editingShop.adcode && this.editingShop.location) {
        callback();
      } else {
        callback(new Error('定位地址获取不到正确经纬度,请重新定位'));
      }
    };
    return {
      // 表格数据源
      gridDataSource: [],
      // 当前分页数据开始index
      startIndex: 0,
      // 当前分页数据结束index
      endIndex: 0,
      currentSelectedRow: null,
      gridDataIsLoading: false,
      // 编辑窗体的状态是否是新增状态
      editDialogIsNewMode: true,
      // 分页配置
      paginationConfig: { selectedPageSize: 10, currentQueryPage: 0 },
      // 编辑层是否显示
      editShopDialogOpend: false,
      //  正在编辑的model
      editingShop: {
        shopId: 0,
        name: '',
        description: '',
        score: 0,
        minPrice: 0,
        deliveryPrice: 0,
        sellCount: 0,
        bulletin: '',
        uisupports: [],
        supports: [],
        avatar: '',
        infos: [],
        uiinfos: [],
        location: '',
        adcode: '',
        gpsaddress: '',
        detailaddress: '',
        appid: ''
      },
      // 是否显示验证结果
      validateable: false,
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '店铺名称必填' },
          { type: 'string', max: 50, message: '微信APPID必须小于50个字' }
        ],
        gpsaddress: [
          { required: true, message: '定位地址必填' },
          { trigger: 'change', validator: validateaddressrequired }
        ]
      },
      // 左树当前选中的app
      selectedApp: null,
      // 左樹的數據
      appinfos: [],
      // 左树的属性
      defaultProps: {
        children: 'children',
        label: 'appname'
      },
      // 指定货品
      selecteGoods: [],
      allGoods: [],
      defaultGoodDialogOpend: false
    };
  },
  methods: {
    onTreeSelected(selecteddata, selectednode) {
      this.selectedApp = selecteddata.appid;
    },
    RefreshTable(appid = '') {
      NProgress.start();
      this.$http.get('/WechatMallOss/Shop/GetShopsByAppId', {
        params: {
          appid: appid
        }
      }).then((response) => {
        if (response.data.isSuccess) {
          this.gridDataSource = response.data.shops;
          NProgress.done();
        }
      }).catch(() => {
        NProgress.done();
      });
    },
    /**
     * 刷新树
     */
    InitTree() {
      NProgress.start();
      let GetAllGoods = this.$http.get('/WechatMallOss/Good/GetAllGoods').then((response) => {
        if (response.data.isSuccess) {
          this.allGoods = [];
          response.data.goods.forEach((good) => {
            this.allGoods.push({ gsid: good.basic.gsid, gsname: good.basic.gsname });
          });
        }
      });
      let GetApp = this.$http.get('/WechatMallOss/App/GetApps').then((response) => {
        if (response.data.isSuccess) {
          this.appinfos.splice(0, this.appinfos.length);
          let children = [];
          response.data.appinfos.forEach((item) => {
            children.push(item.basicinfo);
          });
          this.appinfos.push({ appid: null, appname: '全部商户', children: children });
        }
      });
      this.$http.all([GetAllGoods, GetApp]).then(() => {
        NProgress.done();
      }).catch(() => {
        NProgress.done();
      });
    },
    computeDataIndex(pageNo, pageSize) {
      this.startIndex = pageSize * (pageNo - 1) + 1;
      this.endIndex = this.startIndex + pageSize;
    },
    /** 添加优惠信息  */
    addSupports() {
      this.editingShop.uisupports.push({
        supporttype: '',
        supportremark: ''
      });
    },
    /** 添加店铺描述信息  */
    addInfos() {
      this.editingShop.uiinfos.push({
        infotext: ''
      });
    },
    // 移除店铺描述信息
    removeInfo(index) {
      this.editingShop.uiinfos.splice(index, 1);
    },
    // 移除店铺优惠信息
    removeSupport(index) {
      this.editingShop.uisupports.splice(index, 1);
    },
    // 搜索地址
    querySearchAsync(queryString, callback) {
      let results = [];
      if (queryString) {
        this.$http.get('/WechatMall/Map/SerchByKeywords', {
          params: {
            keywords: queryString,
            citycode: ''
          }
        }).then((response) => {
          if (response.data.isSuccess) {
            response.data.tips.forEach((tip) => {
              tip.value = tip.district + tip.address + '(' + tip.name + ')';
            });
            results = response.data.tips;
            callback(results);
          }
        });
      }
    },
    closeShopForm() {
      this.validateable = false;
      this.$refs['shopForm'].resetFields();
    },
    handleSelect(item) {
      this.editingShop.selectedaddress = item.value;
      this.editingShop.gpsaddress = this.editingShop.selectedaddress;
      this.editingShop.adcode = item.adcode;
      this.editingShop.location = item.location;
    },
    openEditShopDialog(row, isnew) {
      this.editDialogIsNewMode = isnew;
      if (isnew) {
        this.editingShop.shopId = 0;
        this.editingShop.name = '';
        this.editingShop.description = '';
        this.editingShop.score = 0;
        this.editingShop.infos = [];
        this.editingShop.minPrice = '';
        this.editingShop.deliveryPrice = '';
        this.editingShop.avatar = '';
        this.editingShop.selectedaddress = '';
        this.editingShop.bulletin = '';
        this.editingShop.uisupports = [{
          supporttype: '',
          supportremark: ''
        }];
        this.editingShop.supports = [];
        this.editingShop.uiinfos = [{
          infotext: ''
        }];
        this.editingShop.location = '';
        this.editingShop.adcode = '';
        this.editingShop.gpsaddress = '';
        this.editingShop.selectedaddress = '';
        this.editingShop.detailaddress = '';
        this.editingShop.appid = this.selectedApp;
      } else {
        this.editingShop.shopId = row.shopId;
        this.editingShop.name = row.name;
        this.editingShop.description = row.description;
        this.editingShop.score = row.score;
        this.editingShop.minPrice = row.minPrice;
        this.editingShop.deliveryPrice = row.deliveryPrice;
        this.editingShop.avatar = row.avatar;
        this.editingShop.selectedaddress = row.selectedaddress;
        this.editingShop.bulletin = row.bulletin;
        this.editingShop.location = row.location;
        this.editingShop.adcode = row.adcode;
        this.editingShop.gpsaddress = row.gpsaddress;
        this.editingShop.selectedaddress = row.gpsaddress;
        this.editingShop.detailaddress = row.detailaddress;
        this.editingShop.appid = row.appid;
        this.editingShop.uisupports.splice(0, this.editingShop.uisupports.length);
        this.editingShop.uiinfos.splice(0, this.editingShop.uiinfos.length);
        if (row.supports[0]) {
          row.supports.forEach((support) => {
            console.log(support);
            this.editingShop.uisupports.push(support);
          });
        } else {
          this.editingShop.uisupports = [{
            supporttype: '',
            supportremark: ''
          }];
        }
        if (row.infos[0]) {
          row.infos.forEach((info) => {
            console.log(info);
            this.editingShop.uiinfos.push({
              infotext: info
            });
          });
        } else {
          this.editingShop.uiinfos = [{
            infotext: ''
          }];
        }
      }
      this.editShopDialogOpend = true;
    },
    /**
     * 分页变化
     */
    onPageSizeChanged(size) {
      this.paginationConfig.selectedPageSize = size;
      this.computeDataIndex(this.paginationConfig.currentQueryPage, size);
    },
    onPageNoChanged(page) {
      this.paginationConfig.currentQueryPage = page;
      this.computeDataIndex(page, this.paginationConfig.selectedPageSize);
    },
    /**
     * 表格selectchanged
     */
    onSelectionChanged(select) {
      this.currentSelectedRow = select;
    },
    handleAvatarSuccess(res, file) {
      if (res.isSuccess && res.savedObjects) {
        this.editingShop.avatar = axios.defaults.baseURL + '/img/get?img=' + res.savedObjects[0].fileName;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    /**
     * 提交新增app表单
     */
    handleEditAppSubmit() {
      this.validateable = true;
      this.$refs.shopForm.validate((valid) => {
        if (valid) {
          let supports = this.editingShop.uisupports.filter((support) => {
            return support.supporttype;
          });
          this.editingShop.supports = supports;
          this.editingShop.uiinfos.forEach(uiinfo => {
            if (uiinfo.infotext) {
              this.editingShop.infos.push(uiinfo.infotext);
            }
          });
          this.$http.post('/WechatMallOss/Shop/SaveShopInfo', this.editingShop).then((response) => {
            if (response.data.isSuccess) {
              this.$message({
                message: '保存成功!',
                type: 'success'
              });
              if (response.data.shop) {
                let updateIndex = this.gridDataSource.findIndex((shop) => {
                  return shop.shopId === response.data.shop.shopId;
                });
                if (updateIndex > -1) {
                  this.gridDataSource.splice(updateIndex, 1, response.data.shop);
                } else {
                  this.gridDataSource.push(response.data.shop);
                }
              }
              this.editShopDialogOpend = false;
            } else {
              this.$message({
                message: '数据提交出现错误,请稍后重试!',
                type: 'error'
              });
            }
          }).catch(() => {
            this.$message({
              message: '数据提交出现错误,请稍后重试!',
              type: 'error'
            });
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 删除app
     */
    deleteShop(index, row) {
      console.log(row);
      let shopId = row.shopId;
      if (shopId) {
        this.$confirm('删除店铺信息后,此店铺将不能恢复, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete('/WechatMallOss/shop/deleteShop', {
            params: {
              shopId: shopId
            }
          }).then((response) => {
            if (response.data.isSuccess) {
              this.gridDataSource.splice(index, 1);
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
            }
          });
        }
          );
      }
    },
    /**
    * 指定下属货品
    */
    handleSetGoodsubmit() {
      let shopid = this.currentSelectedRow.shopId;
      if (shopid) {
        this.$http.post('/WechatMallOss/Shop/SaveShopGsRelationShip', {
          shopid: shopid,
          gsids: this.selecteGoods
        }).then((response) => {
          if (response.data.isSuccess) {
            this.$message({
              message: '指定物品成功!',
              type: 'success'
            });
            this.defaultGoodDialogOpend = false;
          }
        }).catch(() => {
          this.$message({
            message: '数据保存失败!',
            type: 'error'
          });
        });
      }
    },
    setShopGoods(row) {
      this.currentSelectedRow = row;
      console.log(this.currentSelectedRow);
      let shopid = this.currentSelectedRow.shopId;
      if (shopid) {
        this.$http.get('/WechatMallOss/Good/GetGoodsByShopid', {
          params: {
            shopid: shopid
          }
        }).then((response) => {
          if (response.data.isSuccess) {
            this.selecteGoods.splice(0, this.selecteGoods.length);
            response.data.goods.forEach((good) => { this.selecteGoods.push(good.basic.gsid); });
            this.defaultGoodDialogOpend = true;
          }
        });
      }
    }
  },
  created() {
    this.InitTree();
  },
  watch: {
    selectedApp(value) {
      this.RefreshTable(value);
    }
  },
  computed: {
    uploadUrl() {
      let jwt = Utils.GetLocalData('zillionossjwt');
      return axios.defaults.baseURL + '/img/upload?token=' + jwt;
    },
    GridPageList() {
      if (this.gridDataSource && this.gridDataSource.length > 0) {
        if (this.startIndex > 0 && this.endIndex > 0) {
          return this.gridDataSource.slice(this.startIndex - 1, this.endIndex - 1);
        } else {
          return [];
        }
      } else {
        return [];
      }
    },
    dataCount() {
      if (this.gridDataSource) {
        return this.gridDataSource.length;
      } else {
        return 0;
      }
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.app-container {
  height: 100%;
  .el-row {
    height: 100%;
    .el-col {
      height: 100%;
      .left-tree {
        height: 100%;
        .el-tree {
          height: 100%;
        }
      }
    }
  }
  .shop-dialog {
    .lable-span {
      font-size: 14px;
      color: #48576a;
      font-weight: 700;
      margin-bottom: 12px;
    }
    .shop_img {
      margin-top: 12px;
      width: 178px;
      height: 178px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
      .avatar {
        width: 178px;
        height: 178px;
      }
      .deaultavatar {
        width: 130px;
        height: 130px;
        background-repeat: no-repeat;
        border: none;
        background-image: url('./deaultavatar.png');
      }
    }
  }
}
</style>
